package conf

import (
	"fmt"
	"gitee.com/gcom/stockdock/comm"
	"gitee.com/gcom/stockdock/core/support"
	"github.com/jinzhu/gorm"
	"go.uber.org/zap"
	"time"
)

func InitDB() {
	dbconf := Settings.Database
	db, e := gorm.Open("mysql", fmt.Sprintf("%s:%s@%s?charset=utf8&parseTime=True&loc=Local",
		dbconf.Username, dbconf.Password, dbconf.Url))
	if e != nil {
		comm.Log.Panicf("初始数据库失败%v", e)
	}
	db = db.LogMode(true)
	support.RegisterTracerCtxDecor(func(ctx support.TracerCtx) {
		db = db.New().InstantSet(support.TracerCtxKey, ctx)
		db.SetLogger(GetGormLog(ctx.Logger))
		ctx.DB = db
	})
}

func GetGormLog(l *zap.SugaredLogger) dbLogger {
	return dbLogger{l: l.Desugar().WithOptions(zap.AddCallerSkip(7))}
}

type dbLogger struct {
	l *zap.Logger
}

func (l dbLogger) Print(v ...interface{}) {
	if len(v) > 2 {
		if v[0] == "sql" {
			l.l.Info("gorm.sql", zap.String("SQL", v[3].(string)),
				zap.Any("parameters", v[4]),
				zap.Duration("duration", v[2].(time.Duration)),
				zap.Int64("affected_rows", v[5].(int64)),
				zap.String("source", v[1].(string)),
			)
		} else {
			l.l.Info("gorm.log", zap.Any("values", v[2:]),
				zap.String("source", v[1].(string)),
			)
		}
	}
}
